<template>
  <div class="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-50">
        <!-- 验证码对话框 -->
        <el-dialog v-model="verifyDialogVisible" title="请输入验证码" width="400px" :show-close="false" :close-on-click-modal="false">
      <el-input v-model="verifyCode" placeholder="请输入验证码" class="mb-4"></el-input>
      <template #footer>
        <el-button type="primary" @click="fetchPaperInfo">确定</el-button>
      </template>
    </el-dialog>

    <!-- 顶部导航栏 -->
    <div class="bg-white shadow-sm p-4">
      <div class="container mx-auto flex justify-between items-center">
        <div class="flex items-center">
          <h1 class="text-xl font-bold text-gray-800">智能测试分享</h1>
        </div>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="container mx-auto p-4 flex flex-col justify-center min-h-[calc(100vh-64px)]">
      <!-- 试卷信息卡片 -->
      <div class="bg-gradient-to-br from-orange-400 to-yellow-400 rounded-3xl p-[2px] mb-8 w-full max-w-2xl mx-auto transform hover:scale-[1.02] transition-all duration-300">
        <div class="bg-white rounded-3xl p-8 backdrop-blur-xl">
          <div class="text-center space-y-3 mb-8">
            <h2 class="text-xl font-semibold text-gray-800">
              {{ paperInfo.title }}
            </h2>
            <div class="text-gray-500 flex items-center justify-center gap-2">
              <el-icon>
                <Calendar />
              </el-icon>
              <span>{{ formatDate(paperInfo.created_at) }}</span>
            </div>
          </div>

          <!-- 测试信息标签 -->
          <div class="flex flex-wrap justify-center gap-3">
            <el-tag class="!rounded-full !px-4 !py-2 !text-sm" effect="light" type="warning">
              <el-icon class="mr-1">
                <Monitor />
              </el-icon>
              {{ paperInfo.type === 1 ? '能力测评' : '单元测试' }}
            </el-tag>
            <el-tag class="!rounded-full !px-4 !py-2 !text-sm" effect="light" type="warning">
              <el-icon class="mr-1">
                <Collection />
              </el-icon>
              {{ paperInfo.subject_name }}
            </el-tag>
            <el-tag class="!rounded-full !px-4 !py-2 !text-sm" effect="light" type="warning">
              <el-icon class="mr-1">
                <User />
              </el-icon>
              {{ paperInfo.grade_name }}
            </el-tag>
            <el-tag class="!rounded-full !px-4 !py-2 !text-sm" effect="light" type="warning">
              <el-icon class="mr-1">
                <Calendar />
              </el-icon>
              {{ paperInfo.term_type_name }}
            </el-tag>
            <el-tag class="!rounded-full !px-4 !py-2 !text-sm" effect="light" type="warning">
              <el-icon class="mr-1">
                <Reading />
              </el-icon>
              {{ paperInfo.version_name }}
            </el-tag>
            <el-tag class="!rounded-full !px-4 !py-2 !text-sm" effect="light" type="warning">
              <el-icon class="mr-1">
                <List />
              </el-icon>
              {{ paperInfo.question_total }}题
            </el-tag>
          </div>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="flex flex-wrap justify-center gap-4 mb-8">
        <el-button type="primary"
          class="!rounded-full !px-8 !py-3 !text-base !font-medium !bg-gradient-to-r !from-blue-500 !to-blue-600 !border-none"
          @click="goToTest">
          <el-icon class="mr-2">
            <Edit />
          </el-icon>开始答题
        </el-button>
        <!-- <el-button class="!rounded-full !px-8 !py-3 !text-base !font-medium" 
          @click="activeView = 'analysis'">
          <el-icon class="mr-2">
            <View />
          </el-icon>查看解析
        </el-button> -->
        <el-button class="!rounded-full !px-8 !py-3 !text-base !font-medium" 
          @click="goToAnalysis">
          <el-icon class="mr-2">
            <Printer />
          </el-icon>查看试卷
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, defineAsyncComponent } from 'vue';
import { useRoute,useRouter } from 'vue-router';
import { ElMessage, ElDialog } from 'element-plus';
import {
  Calendar,
  Monitor,
  Collection,
  User,
  Reading,
  List,
  Edit,
  View,
  Printer
} from '@element-plus/icons-vue';
import { getPaperDetail } from '@/api/share'; // 假设有这个API

const router = useRouter();
const route = useRoute();
const paperId = ref('');
const paperInfo = ref({
  title: '智能测试试卷',
  created_at: new Date().toISOString(),
  type: 1,
  subject_name: '数学',
  grade_name: '一年级',
  term_type_name: '上学期',
  version_name: '人教版',
  question_total: 10
});

// 格式化日期的函数
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return `${date.getFullYear()}.${String(date.getMonth() + 1).padStart(2, '0')}.${String(date.getDate()).padStart(2, '0')}`;
};

const verifyDialogVisible = ref(true);
const verifyCode = ref('');
const tempStorageKey = 'share_quiz_verify_code';


// 跳转答题页面
const goToTest = () => {
  router.push({
    name: 'shareAnalysisQuestions',
  });
};

// 跳转解析页面
const goToAnalysis = () => {
  router.push({
    name: 'shareAnalysisPaper',  
  });
};

const fetchPaperInfo = async () => {
  try {
    // 从URL获取试卷ID
    if (!paperId.value && route.query.id) {
      paperId.value = route.query.id;
    }
    if ((!route.query.id || !route.query.id.trim()) && (!paperId.value || !paperId.value.trim())) {
      ElMessage.error('试卷ID不存在或为空');
      return;
    }
    const data = {
      id: paperId.value,
      share_code: verifyCode.value
    }
    console.log("data", data);
    
    // 获取试卷详情
    const res = await getPaperDetail(data);
    if (res.paper) {
      paperInfo.value = res.paper;
      // 验证通过，保存验证码到临时缓存
      sessionStorage.setItem(tempStorageKey, JSON.stringify({
        share_code: verifyCode.value,
        paper_id: paperId.value,
        expires: Date.now() + 7 * 24 * 60 * 60 * 1000 // 7天后过期
      }));
      verifyDialogVisible.value = false;
    } else {
      ElMessage.error('验证码错误或无效');
    }
  } catch (error) {
    // console.error('获取试卷信息出错:', error);
    ElMessage.error('获取试卷信息出错');
  }
};

// 检查是否有缓存的验证码
onMounted(() => {
    const cachedData = JSON.parse(sessionStorage.getItem(tempStorageKey)) || '';
    if (cachedData) {
        verifyCode.value = cachedData.share_code;
        paperId.value = cachedData.paper_id;
        verifyDialogVisible.value = false;
        fetchPaperInfo();
    }
});
</script>

<style scoped>
/* 可以添加一些自定义样式 */
</style>